import utils from '../../../utils/util.js' //工具库
import api from '../../../api/api.js'
import load from '../../templates/loader/loader.js' //载入动画框
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressList: "",
    orderItem: [],
    orderArray: [],
    totalCount: 0,
    totalPrice: 0.00,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    var order = decodeURI(decodeURI(options.order));
    var ordetObj = JSON.parse(order);
    that.data.sgin = options.sgin;
    //初始化载入等待动画
    that.loader = load.loader(that, {
      data: "loader",
      toast: true,
      size: 50,
      borderWidth: 3
    });
    ordetObj.forEach(function (item) {
      item.child.forEach(function (item) {
        var _number = parseInt(item.number)
        that.data.totalCount += _number
        that.data.totalPrice += (item.price * _number)
        that.data.orderArray.push(item.cart_id)
        that.data.shop_id = item.shop_id
        that.data.crowdfundingId = item.crowdfundingId || 0
      })
    })
    //获取用户信息
    api.getUser({
      done: (user) => {
        wx.login({
          success: function (data) {
            console.log(data)
            that.data.code = data.code
          }
        })
        that.setData({
          orderItem: ordetObj,
          totalCount: that.data.totalCount,
          totalPrice: utils.format(that.data.totalPrice),
          userInfo: user,
        })
      }
    })
  },
  onShow: function () {
    var that = this
    that.loader.open()
    //获取用户信息
    api.getUser({
      done: (user) => {
        that.data.userInfo = user
        that.getAddressList()
      },
      fail: () => {
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }
    })
  },
  getAddressList: function () {
    var that = this
    //获取地址列表
    console.log(that.data.userInfo)
    var jsonStr = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"userId":"' + that.data.userInfo.id + '","id":""}}';
    api.getAddressList({
      method: 'POST',
      data: {
        REQ_MESSAGE: jsonStr
      },
      success: (res) => {
        that.loader.close()
        var empty = that.data.empty
        if (res.rows) {
          res.rows.forEach(function (item) {
            if (item.default_address == 1) {
              res.rows = item
            }
          })
          if (res.rows.length == 0) {
            res.rows = ""
          }
          that.setData({
            addressList: res.rows
          });
        } else {
          wx.showToast({
            title: '获取收货地址失败',
            image: '/image/ico/error-ico.png'
          })
        }
      },
      fail: (res) => {
        wx.showToast({
          title: '获取收货地址失败',
          image: '/image/ico/error-ico.png'
        })
      }
    })
  },
  //提交生成订单
  sbOrder: function () {
    var that = this
    var orderStr = that.data.orderArray.join(",")
    that.loader.open()
    if (!that.data.addressList.id) {
      that.loader.close()
      wx.showModal({
        title: '提示',
        showCancel: false,
        confirmColor: "#e30c26",
        content: '请添加收获地址'
      })
      return
    }
    var json = '{}'
    if (that.data.sgin == 1) {
      json = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"goodsId":"' + that.data.shop_id + '","userId":' + that.data.userInfo.id + ',"addressId":' + that.data.addressList.id + ',"crowdfundingId":"' + that.data.crowdfundingId + '","number":' + that.data.totalCount + ',"msg":"备注信息"}}'
      api.getDetailOrder({
        method: 'POST',
        data: {
          REQ_MESSAGE: json
        },
        success: (res) => {
          console.log("详情订单", res)
          that.orderCallBack(res)
        },
        fail: (res) => {
          wx.showToast(api.statusFail)
          console.log("详情订单", res)
        },
        complete: (res) => {
          that.loader.close()
        }
      })
    } else {
      json = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"shopcartId":"' + orderStr + '","userId":' + that.data.userInfo.id + ',"crowdfundingId":' + that.data.crowdfundingId + ',"addressId":"' + that.data.addressList.id + '","msg":"备注信息"}}'
      api.setOrder({
        method: 'POST',
        data: {
          REQ_MESSAGE: json
        },
        success: (res) => {
          that.orderCallBack(res)
        },
        fail: (res) => {
          wx.showToast(api.statusFail)
        },
        complete: (res) => {
          that.loader.close()
        }
      });
    }
  },
  orderCallBack: function (res) {
    var that = this;
    if (res) {
      if (res.REP_BODY.RSPCOD == "000000") {
        wx.showToast({
          title: '订单提交成功!',
          icon: 'success',
          duration: 2000
        })
        that.pay(res.REP_BODY.orderId); //调启支付
      } else {
        wx.showToast({
          title: '订单提交失败!',
          image: '/image/ico/error-ico.png',
          duration: 2000
        })
      }
    } else {
      wx.showToast({
        title: '订单提交失败!',
        image: '/image/ico/error-ico.png',
        duration: 2000
      })
    }
  },
  pay: function (orderId) {
    var that = this
    var orderStr = that.data.orderArray.join(",")
    wx.showLoading({
      mask:true
    })
    api.payOrder({
      method: 'POST',
      data: {
        orderId: orderId,
        code: that.data.code,
        userId:that.data.userInfo.id
      },
      success: (res) => {
        wx.hideLoading()
        if (res) {
          wx.requestPayment({
            'timeStamp': res.timeStamp,
            'nonceStr': res.nonceStr,
            'package': res.packageValue,
            'signType': 'MD5',
            'paySign': res.sign,
            'success': function (res) {
              if (res.errMsg == "requestPayment:ok") {
                wx.redirectTo({
                  url: '/pages/order/orderlist/orderlist?type=1',
                })
              } else {
                wx.showToast({
                  title: '支付失败!',
                  image: '/image/ico/error-ico.png',
                  duration: 2000
                })
              }
            },
            'fail': function (res) {
              if (res.errMsg == "requestPayment:fail cancel") {
                wx.redirectTo({
                  url: '/pages/order/orderlist/orderlist?type=0',
                })
              } else {
                wx.showToast({
                  title: '支付失败!',
                  image: '/image/ico/error-ico.png',
                  duration: 2000
                })
              }
              console.log("payFail", res);
            }
          })
        } else {
          wx.showToast({
            title: '缺少参数!',
            image: '/image/ico/error-ico.png',
            duration: 2000
          })
        }
      },
      fail: (res) => {
        console.log(res)
      }
    })
  }
})